#!/usr/bin/env python
# -*- conding: utf-8 -*-

"""
@Time     : 2024/8/5 23:21
@Author   : liujingmao
@File     : app_handler.py
"""
import os
import uuid
from dataclasses import dataclass

from injector import inject
from openai import OpenAI

from internal.exception import FailException
from internal.model import App
from internal.schema.app_schema import CompletionReq
from internal.service import AppService, VectorDatabaseService
from pkg.response import success_json, validate_error_json, success_message


@inject
@dataclass
class AppHandler:
    """应用控制器"""
    app_service: AppService
    vector_data_service: VectorDatabaseService

    def create_app(self):
        """调用服务创建新的APP记录"""
        app = self.app_service.create_app()
        return success_message(f"应用已经成功创建，id为:{app.id}")

    def get_app(self, id: uuid.UUID) -> App:
        app = self.app_service.get_app(id)
        return success_message(f"应用已经成功获取,应用名是:{app.name}")

    def update_app(self, id: uuid.UUID):
        app = self.app_service.update_app(id)
        return success_message(f"应用已经成功获取,"
                               f"应用名是:{app.name},应用描述是：{app.description}")

    def delete_app(self, id: uuid.UUID):
        app = self.app_service.delete_app(id)
        return success_message(f"应用已经成功删除，应用名：{app.name},id:{app.id}")

    def ping(self):
        raise FailException("数据没有找到")

    def completion(self):
        # 1. 提取从接口中获取的输入 GET POST
        req = CompletionReq()
        if not req.validate():
            return validate_error_json(req.errors)
        # 2. 构建OpenAI客户端，并发起请求
        client = OpenAI(api_key=os.getenv("api_key"), base_url=os.getenv("base_url"))
        # 3. 得到请求响应，然后将OpenAI的响应传递给前端
        completion = client.chat.completions.create(
            model="moonshot-v1-8k",
            messages=[
                {"role": "system",
                 "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，"
                            "你更擅长中文和英文的对话。你会为用户提供安全，"
                            "有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，"
                            "种族歧视，黄色暴力等问题的回答。Moonshot AI "
                            "为专有名词，不可翻译成其他语言。"},
                {"role": "user", "content": req.query.data},
            ]
        )
        # 4. 通过 API 我们获得了 Kimi 大模型给予我们的回复消息（role=assistant）
        content = completion.choices[0].message.content
        return success_json(data={"content": content})

    def completionv2(self):

        """聊天接口"""
        # 1.提取从接口中获取的输入，POST
        req = CompletionReq()
        if not req.validate():
            return validate_error_json(req.errors)

        # 2.构建OpenAI客户端，并发起请求
        # client = OpenAI(base_url=os.getenv("OPENAI_API_BASE"))
        client = OpenAI()

        # 3.得到请求响应，然后将OpenAI的响应传递给前端
        completion = client.chat.completions.create(
            model="gpt-3.5-turbo-16k",
            messages=[
                {"role": "system", "content": "你是OpenAI开发的聊天机器人，请根据用户的输入回复对应的信息"},
                {"role": "user", "content": req.query.data},
            ]
        )

        content = completion.choices[0].message.content

        return success_json({"content": content})
